<template>
  <el-dialog
    class="refundDialog"
    v-model="props.forRefundVisible"
    :title="props.refundForm?.title"
    width="60%"
    :show-close="false"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-row class="row">
        <el-col :span="11">
          <el-form-item label="时间筛选">
            <el-date-picker
              v-model="detaArray"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              size="default"
              value-format="YYYY-MM-DD"
              @change="pickerChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="关联工单号" prop="applyId">
            <el-select
              v-model="applyId"
              class="m-2"
              placeholder="可输入工单号或下拉选择"
              style="width: 65%"
              filterable
              clearable
              @change="changeApplyByOrderNum"
            >
              <el-option
                v-for="item in applyIdNums"
                :key="item.orderNum"
                :label="item.orderNum"
                :value="item.orderNum"
              />
            </el-select>
            <el-input
              v-model="retrievalType"
              :disabled="true"
              style="width: 35%"
              placeholder="申请类型"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="row">
        <el-col :span="11">
          <el-form-item
            label="原申请单号"
            prop="applyNum"
            :rules="{
              required: true,
              message: '可输入原申请单号进行选择',
              trigger: 'change'
            }"
          >
            <el-select
              v-model="ruleForm.applyNum"
              class="m-2"
              placeholder="请选择原申请单号"
              style="width: 100%"
              @change="applyChange"
              filterable
              clearable
            >
              <el-option
                v-for="item in applyNums"
                :key="item.applyNum"
                :label="item.applyNum"
                :value="item.applyNum"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="退还申请人" prop="dealApplyUser">
            <el-input
              v-if="props.refundForm?.type == 'for'"
              v-model="dealApplyUserName"
              :disabled="true"
              style="width: 100%"
            ></el-input>
            <el-select
              v-else
              v-model="dealApplyUser"
              class="m-2"
              placeholder="请选择"
              style="width: 100%"
              @change="dealUserChange"
            >
              <el-option
                v-for="item in dealUsers"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="row">
        <el-col :span="11">
          <el-form-item
            label="退还审批人"
            prop="dealUser"
            :rules="{
              required: true,
              message: '请选择审批人',
              trigger: 'change'
            }"
          >
            <el-input
              v-if="props.refundForm?.type == 'add'"
              v-model="dealApplyUserName"
              :disabled="true"
              style="width: 100%"
            ></el-input>
            <el-select
              v-else
              v-model="ruleForm.dealUser"
              class="m-2"
              placeholder="请选择"
              style="width: 100%"
              @change="userChange"
            >
              <el-option
                v-for="item in dealUsers"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="row">
        <el-col>
          <el-form-item label="备件退还选择">
            <div>提示：先勾选退还备件，即可输入退还数量</div>
            <el-table
              :data="refundDetailList"
              border
              style="width: 100%"
              @selection-change="selectionChange"
              @select="selectRow"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="partNum" label="备件编号" />
              <el-table-column prop="partName" label="备件名称" />
              <el-table-column prop="partTypeName" label="备件类型" />
              <el-table-column
                prop="amount"
                label="可申请退还数量"
                width="180"
              />
              <el-table-column prop="price" label="备件价值(元)" width="160" />
              <el-table-column
                prop="batchNum"
                label="退还批次"
                v-if="props.refundForm?.type == 'add'"
              />
              <el-table-column
                prop="num"
                label="退还数量"
                v-if="props.refundForm?.type == 'for'"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.num"
                    autocomplete="off"
                    placeholder="输入数量"
                    @change="inputChange(scope.row)"
                    :disabled="!tableSelectedIds.includes(scope.row.partNum)"
                    onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^123456789]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
                    onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-19]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="num"
                label="退还数量"
                v-if="props.refundForm?.type == 'add'"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.num"
                    autocomplete="off"
                    placeholder="输入数量"
                    @change="inputChange(scope.row)"
                    :disabled="!tableSelectedIds.includes(scope.row.batchNum)"
                    onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^123456789]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
                    onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-19]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="row" v-if="props.refundForm?.type == 'add'">
        <el-col>
          <el-form-item label="备注">
            <el-input
              v-model="ruleForm2.remark"
              autocomplete="off"
              placeholder="请输入备注"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div style="text-align: right">
        <div>
          <el-button @click="cancel(ruleFormRef)"> 取消 </el-button>
          <el-button
            type="primary"
            @click="submit(ruleFormRef)"
            :loading="loading"
            >确认</el-button
          >
        </div>
      </div>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { ref, reactive, watch, nextTick } from 'vue'
import { getDirectorListApi } from '/@/api/publicApi'
import {
  getApplyByOrderNumApi,
  getUsageByApplyNumApi,
  getUsageDetailByApplyNumApi,
  savePartRefundAndWarehouseApi,
  savePartRefundApi
} from '/@/api/spare'
import { Session } from '/@/utils/storage'
const emit = defineEmits(['cancelRefund', 'submitRefund'])
const props = defineProps({
  forRefundVisible: Boolean,
  refundForm: Object
})
const userInfo = Session.get('shebei')
const formSize = ref('default')
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()
const dealUsers = ref<any>([])
const applyIdNums = ref<any>([])
const applyNums = ref<any>([])
const refundDetailList = ref<any>([])
const tableSelectedIds = ref<any>([])
const retrievalType = ref<any>('')
const applyId = ref<any>('')
const detaArray = ref<any>([])
const ruleForm = ref({
  applyNum: '',
  dealUser: '',
  dealUserName: '',
  refundDetailList: <any>[]
})
const ruleForm2 = ref({
  applyNum: '',
  refundUser: '',
  refundUserName: '',
  detailRequests: <any>[],
  remark: ''
})
const dealApplyUser = ref('')
const dealApplyUserName = ref('')

const validateApplyId = (rule: any, value: any, callback: any) => {
  if (applyId.value == '') {
    callback(new Error('请输入工单号'))
  } else {
    callback()
  }
}
const validateDealApplyUser = (rule: any, value: any, callback: any) => {
  if (dealApplyUser.value == '') {
    callback(new Error('请选择退还申请人'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  applyId: [{ required: true, validator: validateApplyId, trigger: 'blur' }],
  dealApplyUser: [
    { required: true, validator: validateDealApplyUser, trigger: 'change' }
  ]
})

const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  applyId.value = ''
  ruleForm.value.applyNum = ''
  retrievalType.value = ''
  emit('cancelRefund')
}
const submit = (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      if (props.refundForm?.type == 'for') {
        savePartRefundApi(ruleForm.value).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: 'success',
              message: '申请成功'
            })
            applyId.value = ''
            ruleForm.value.applyNum = ''
            retrievalType.value = ''
            formEl.resetFields()
            emit('submitRefund')
          } else {
            applyId.value = ''
            ruleForm.value.applyNum = ''
            retrievalType.value = ''
            refundDetailList.value = []
            formEl.resetFields()
          }
        })
      } else {
        savePartRefundAndWarehouseApi(ruleForm2.value).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: 'success',
              message: '添加成功'
            })
            applyId.value = ''
            ruleForm.value.applyNum = ''
            retrievalType.value = ''
            formEl.resetFields()
            emit('submitRefund')
          } else {
            applyId.value = ''
            ruleForm.value.applyNum = ''
            retrievalType.value = ''
            refundDetailList.value = []
            formEl.resetFields()
          }
        })
      }
      loading.value = false
    } else {
      loading.value = false
    }
  })
}

//时间筛选
const pickerChange = () => {
  getApplyByOrderNum('')
}

const getApplyByOrderNum = (val: any) => {
  let params = {
    orderNum: val,
    startTime: detaArray.value ? detaArray.value[0] : '',
    endTime: detaArray.value ? detaArray.value[1] : ''
  }
  getApplyByOrderNumApi(params).then((res) => {
    if (res.code == 0) {
      applyIdNums.value = res.data
    }
  })
}
const changeApplyByOrderNum = (val: any) => {
  if (val != '') {
    applyNums.value = []
    ruleForm.value.applyNum = ''
    refundDetailList.value = []
    applyIdNums.value.forEach((item: any) => {
      if (item.orderNum == val) {
        console.log(item)
        applyNums.value = item.partDetailResponses
        if (item.applyType == 1) {
          retrievalType.value = '维修申请'
        } else if (item.applyType == 2) {
          retrievalType.value = '维保申请'
        } else {
          retrievalType.value = '点检申请'
        }
      }
    })
  } else {
    applyNums.value = []
  }
}
const getUsageByApplyNum = (val: any) => {
  if (val != '') {
    if (props.refundForm?.type == 'for') {
      getUsageByApplyNumApi(val).then((res) => {
        if (res.code == 0) {
          refundDetailList.value = res.data
        }
      })
    } else {
      getUsageDetailByApplyNumApi(val).then((res) => {
        if (res.code == 0) {
          refundDetailList.value = res.data
        }
      })
    }
  }
}

const getDirectorList = () => {
  getDirectorListApi(5).then((res) => {
    if (res.code == 0) {
      dealUsers.value = res.data
      dealUsers.value.forEach((i: any) => {
        if (userInfo.id == i.id) {
          dealApplyUser.value == i.realName
        }
      })
    }
  })
}
getDirectorList()

const selectionChange = (selection: any) => {
  tableSelectedIds.value = []
  if (props.refundForm?.type == 'for') {
    ruleForm.value.refundDetailList = []
    selection.forEach((item: any) => {
      let obj = {
        partId: item.partId,
        amount: item.num
      }
      ruleForm.value.refundDetailList.push(obj)
      tableSelectedIds.value.push(item.partNum)
    })
  } else {
    ruleForm2.value.detailRequests = []
    selection.forEach((item: any) => {
      let obj = {
        partId: item.partId,
        amount: item.num,
        batchNum: item.batchNum
      }
      ruleForm2.value.detailRequests.push(obj)
      tableSelectedIds.value.push(item.batchNum)
    })
  }
}

const selectRow = (selection: any, row: any) => {
  if (selection.indexOf(row) == -1) {
    row.num = ''
  }
}

const userChange = (val: any) => {
  dealUsers.value.forEach((item: any) => {
    if (item.id == val) {
      ruleForm.value.dealUserName = item.realName
    }
  })
}

const dealUserChange = (val: any) => {
  dealUsers.value.forEach((item: any) => {
    if (item.id == val) {
      ruleForm2.value.refundUserName = item.realName
      ruleForm2.value.refundUser = item.id
    }
  })
}

const inputChange = (val: any) => {
  if (props.refundForm?.type == 'for') {
    ruleForm.value.refundDetailList.forEach((i: any) => {
      if (i.partId == val.partId) {
        i.amount = val.num
      }
    })
  } else {
    ruleForm2.value.detailRequests.forEach((i: any) => {
      if (i.partId == val.partId) {
        if (val.num > val.amount) {
          ElMessage({
            type: 'warning',
            message: '退还数量不能大于可退还数量'
          })
          val.num = ''
        } else {
          i.amount = val.num
        }
      }
    })
  }
}
const applyChange = (val: any) => {
  ruleForm2.value.applyNum = val
  getUsageByApplyNum(val)
}

watch(
  () => props.forRefundVisible,
  () => {
    if (props.forRefundVisible == true) {
      var date = new Date()
      var year = date.getFullYear() //月份从0~11，所以加一
      let month = '0' + (date.getMonth() + 1)
      let lastmonth = '0' + date.getMonth()
      let day = date.getDate()
      let toDay = year + '-' + month + '-' + day
      let lastDay = year + '-' + lastmonth + '-' + day
      detaArray.value = [lastDay, toDay]
      getApplyByOrderNum('')
      ruleFormRef.value?.clearValidate('dealApplyUser')
      ruleFormRef.value?.clearValidate('dealUser')
      if (props.refundForm?.type == 'for') {
        dealApplyUser.value = userInfo.id ? userInfo.id : ''
      } else if (props.refundForm?.type == 'add') {
        ruleForm.value.dealUser = userInfo.id ? userInfo.id : ''
      }
      dealApplyUserName.value = userInfo.realName ? userInfo.realName : ''
      refundDetailList.value = []
      applyNums.value = []
    } else {
      dealApplyUser.value = ''
      ruleForm.value.dealUser = ''
    }
  }
)
</script>
<style scoped lang="scss">
.refundDialog {
  .row {
    font-size: var(--el-font-size-base);
    margin-bottom: 15px;
  }
}
</style>
